package com.example.adms.role.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.adms.role.entity.Role;
import com.example.adms.role.mapper.RoleMapper;
import com.example.adms.role.service.RoleService;
import com.example.adms.user.entity.User;
import com.example.adms.vo.Result;
import com.example.adms.role.vo.RoleMenuTree;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 获取用户权限列表，使用角色id查对应权限
     * @param token
     * @return
     */
    @Override
    public Result getRoleListById(String token) {
        //通过token获取用户信息
        String s = redisTemplate.opsForValue().get("Authorization:login:token:" + token);
        User user = JSONObject.parseObject(s, User.class);
        Map<String,Object> map = new HashMap<>();
        map.put("roleId",user.getRoleId());
        map.put("userId",user.getUserId());
        List<RoleMenuTree> list = roleMapper.selectRoleListById(map);
        log.info("list:{}",list);
        return Result.success(list);
    }

    /**
     * 根据用户id查对应角色
     * @param token
     * @return
     */
    @Override
    public Result getRoleById(String token) {
        //通过token获取用户信息
        String s = redisTemplate.opsForValue().get("TOKEN_" + token);
        User user = JSONObject.parseObject(s, User.class);
        Map<String,Object> map = new HashMap<>();
        map.put("uid",user.getId());
        Role role = roleMapper.selectRoleById(map);
        return Result.success(role);
    }

    /**
     * 获取角色列表
     * @return
     */
    @Override
    public Result getRoleList() {
        List<Role> list = this.list();
        return Result.success(list);
    }
}
